<style lang='scss'>
.el-table th {
  background: #fafafa;
  padding: 6px 0 !important;
}

.el-table td div {
  font-size: 12px;
}

.mt10 {
  margin-top: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      @close="modifyDialogVisible = false;"
      :visible.sync="modifyDialogVisible"
      class="view-dialog"
    >
      <el-form label-position="top" :model="modifyForm" ref="modifyForm" class="pl20 mb20" style="max-height:600px;overflow-y:auto;">
        <div class="mb20" style="font-size:16px;font-weight:700;">产品编号:
          <span>{{modifyForm.productCode}}</span>
        </div>

        <div v-for="(contentItem,contentIndex) in modifyForm.content" :key="contentIndex">
          <div class="mt10 mb10">{{contentItem.key+':'}}</div>
          <div class="el-table el-table--fit el-table--border el-table--enable-row-transition">
            <div class="el-table__header-wrapper">
              <table cellspacing="0" cellpadding="0" border="0" class="el-table__header" style="width: 100%;">
                <thead>
                  <tr>
                    <th class="is-leaf">
                      <div class="cell">代码</div>
                    </th>
                    <th class="is-leaf">
                      <div class="cell">参数描述</div>
                    </th>
                    <th class="is-leaf">
                      <div class="cell">参数值</div>
                    </th>
                  </tr>
                </thead>
              </table>
            </div>

            <div class="el-table__body-wrapper">
              <table cellspacing="0" cellpadding="0" border="0" class="el-table__body" style="width: 100%;">
                <tr class="el-table__row" v-for="(item,index) in modifyForm.content[contentIndex].list" :key="index">
                  <td class height="40px">
                    <div class="cell">{{item.code}}</div>
                  </td>

                  <td class height="40px">
                    <div class="cell">{{item.desc}}</div>
                  </td>

                  <td class="tc">
                    <el-form-item
                      :prop=" 'content['+contentIndex+'].list['+index+'].value' "
                      :rules="[


                                {
                                    required:true,message:'请输入参数值', trigger: 'blur'
                                },
                              ]"
                    >
                      <el-input style="width:80%;" :readonly="viewOrEdit == 'view' " v-model="item.value" placeholder="请输入"></el-input>
                    </el-form-item>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>

        <el-row class="mt20 ml20 tc">
          <el-button v-if="viewOrEdit == 'edit' " size="small" type="success" @click="onSubmitForm">保存</el-button>
          <el-button size="small" type="primary" @click="modifyDialogVisible = false;">关闭</el-button>
        </el-row>
      </el-form>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="历史版本"
      @close="historyDialogVisible = false;"
      :visible.sync="historyDialogVisible"
      class="router view-dialog"
    >
      <div class="data-list-container">
        <el-table
          v-loading="regionLoading"
          element-loading-spinner="el-icon-loading"
          :data="queryHistoryList"
          border
          style="width:100%"
          class="m20px"
        >
          <el-table-column label="历史时间" width="140">
            <template slot-scope="scope">{{onDateFormat(scope.row.gmtCreated)}}</template>
          </el-table-column>
          <el-table-column prop="operator" label="操作员" width="120"></el-table-column>
          <el-table-column prop="path" label="全路径"></el-table-column>
          <el-table-column prop="content" label="历史版本内容">
            <template slot-scope="scope">{{scope.row.content}}</template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="openHistoryEditDialog(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-row class="mt20 ml20 tc">
        <el-button size="small" type="primary" @click="historyDialogVisible = false;">关闭</el-button>
      </el-row>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="历史版本编辑"
      @close="historyEditDialogVisible = false;"
      :visible.sync="historyEditDialogVisible"
      class="view-dialog"
    >
      <el-form class="mt20" :model="modifyHistoryForm" :rules="modifyHistoryFormRules" ref="addEditForm" label-width="120px">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="产品编号:" prop="id">
              <el-input placeholder="请输入" readonly v-model="modifyHistoryForm.id"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="操作员:" prop="operator">
              <el-input placeholder="请输入" readonly v-model="modifyHistoryForm.operator"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="历史保存时间:" prop="gmtCreated">
              <el-input placeholder="请输入" readonly v-model="modifyHistoryForm.gmtCreated"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="content:" prop="content">
              <!-- <MonacoEditor :jsonData.sync="modifyHistoryForm.content" ref="jsonData1"></MonacoEditor> -->
              <el-input type="textarea" readonly :autosize="{minRows:20}" placeholder="请输入" v-model="modifyHistoryForm.content"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" class="tc mt20">
            <el-button icon="el-icon-edit" type="success" @click="onOpenRestoreDialog(modifyHistoryForm)">还原该版本</el-button>

            <el-button type="primary" @click="historyEditDialogVisible = false;">关闭</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <div class="data-list-container mt20">
      <el-table
        v-loading="regionLoading"
        element-loading-spinner="el-icon-loading"
        :data="queryNodeInfo"
        border
        style="width:100%"
        class="m20px"
      >
        <el-table-column sortable prop="key" label="序列号" width="80">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column prop="path" label="产品编号"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="openAddOrEditDialog('view',scope.row)">查看</el-button>
            <!--v-if="permissions.updateDuty&&permissions.updateDuty.canUse==1" -->
            <el-button size="small" type="text" @click="openAddOrEditDialog('edit',scope.row)">编辑</el-button>

            <el-button size="small" type="text" @click="openHistoryDialog(scope.row)">历史版本</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import SearchContainer from "src/components/common/SearchContainer";
import SELECT_DATA, { getConfigItem } from "src/utils/selectData";
import storage from 'src/utils/storage';
import fetch from "src/utils/fetch";
import notification from "src/utils/notification";
import MonacoEditor from "src/components/common/MonacoEditor.vue"

import { isJSON, DateFormat } from "src/utils/tools";


export default {
  data() {

    const inputWarning = (msg) => {

      return [
        {
          required: true,
          message: msg,
          trigger: "blur,change"
        }
      ];
    };

    const pagePermissionsMenu = storage.get('pagePermissionsMenu') ? storage.get('pagePermissionsMenu') : {};
    return {

      SELECT_DATA,
      permissions: pagePermissionsMenu.GWXX || {},
      isHaveData: false,
      modifyForm: {

        productCode: '',
        content: [],

      },
      modifyHistoryForm: {
      },

      queryHistoryList: [],

      modifyHistoryFormRules: {
        content: inputWarning('请输入'),
      },

      queryNodeInfo: [],
      viewOrEdit: '',
      modifyFormRules: {
        path: inputWarning('请输入'),
        content: inputWarning('请输入'),
      },
      modifyDialogVisible: false,
      historyDialogVisible: false,
      historyEditDialogVisible: false,
      title: '',
    };
  },
  components: {
    SearchContainer,MonacoEditor
  },
  computed: {
    ...mapGetters(["pagination", "regionLoading",]),
  },
  watch: {

  },
  created() {

    this.onSearch();


  },
  methods: {
    ...mapActions(["doZooHandlerName", 'queryAssetNode']),
    onDateFormat(gmt) {
      return DateFormat(gmt);
    },
    addHistoryRouter(row, cb) {
      let params = {
        path: row.path ? row.path : row.key,
        content: row.content ? row.content : '',
      };

      fetch({
        url: '/zkdata/history',
        type: "post",
        data: params,
        showRegionLoading: true,
        success: (data) => {
          cb && cb(row);

        },
      });

    },
    getHistoryList(path) {
      fetch({
        url: '/zkdata/histories',
        type: "post",
        data: { path: path },
        showRegionLoading: true,
        success: (data) => {
          this.queryHistoryList = data ? data.zkDataHistoryList : [];
        },
      });
    },
    openHistoryDialog(row) {
      this.historyDialogVisible = true;
      this.getHistoryList(row.parentPath + row.path);

    },
    openHistoryEditDialog(data) {

      this.modifyHistoryForm = {
        operator: data.operator,
        gmtCreated: DateFormat(data.gmtCreated),
        content: isJSON(data.content) ? JSON.stringify(JSON.parse(data.content), '{}', 4) : data.content,
        path: data.path,
        id: data.id,
      };
      this.historyEditDialogVisible = true;
    },
    onOpenRestoreDialog(row) {
      let that = this;

      this.$confirm("确定还原改版本吗?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      }).then(() => {

        fetch({
          url: '/config/updateConfig',
          type: "post",
          data: { key: this.modifyHistoryForm.path, content: this.modifyHistoryForm.content },
          showRegionLoading: true,
          success: (data) => {

            notification.success('操作成功');
            row.key = row.path;

            // 添加一条历史操作记录
            this.addHistoryRouter(row, (row) => {
              // 更新历史查询列表
              this.getHistoryList(row.key);
              // 更新路由配置列表
              this.onSearch();
            });

            this.historyEditDialogVisible = false;
          },
        });


      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消"
        });
      });
    },

    openHistoryDialog(row) {
      this.historyDialogVisible = true;
    },
    openHistoryEditDialog() {
      this.modifyHistoryForm = {
        path1: 'test1',
        path2: 'test2',
        path3: 'test3',
        content: 'test4',
      };
      this.historyEditDialogVisible = true;
    },
    onOpenRestoreDialog() {
      this.$confirm("确定还原改版本吗?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      }).then(() => {
        this.historyEditDialogVisible = false;
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消"
        });
      });
    },

    openAddOrEditDialog(type, row) {

      this.$refs["modifyForm"] && this.$refs["modifyForm"].resetFields();
      this.viewOrEdit = type;

      this.title = type == 'view' ? '产品配置-查看' : '产品配置-编辑';
      let fullPath = row.parentPath + row.path;
      this.modifyDialogVisible = true;

      fetch({
        url: '/assets/value',
        type: "post",
        data: { key: fullPath },
        showRegionLoading: true,
        success: (data) => {
          if (!data[fullPath]) return;

          let pageData = JSON.parse(data[fullPath]);
          let content = [];
          this.modifyForm = {
            productCode: '',
            content: [],
          }

          for (let key in pageData) {
            if (key == 'productCode') {
              this.modifyForm[key] = pageData[key];
            } else {
              content.push({ key: key, list: pageData[key] });
            }
          }

          this.modifyForm.content = content;

        },
      });

    },
    //新增&&编辑保存
    onSubmitForm() {
      let that = this;
      let params = {};


      this.$refs.modifyForm.validate(valid => {
        if (valid) {

          // this.$confirm("确定要提交数据吗?", "提示", {
          //   confirmButtonText: "确定",
          //   cancelButtonText: "取消",
          //   type: "warning"
          // }).then(() => {
          let path = '/asset/za-pre-product-config/' + that.modifyForm.productCode;
          let content = {};

          that.modifyForm.content.forEach((item, index) => {
            content[item.key] = item.list;
          })
          content.productCode = that.modifyForm.productCode;

          params.url = '/assets/config';
          params.data = {
            key: path,
            content: JSON.stringify(content),
          }


          params.cb = () => {
            this.modifyDialogVisible = false;
            this.addHistoryRouter(params.data, (row) => {
              this.onSearch();
            })

          };

          this.doZooHandlerName(params);
          // })

        } else {
          this.$message({
            type: "warning",
            message: "请检查表单必填项!"
          });
        }
      });

    },
    onSearch() {

      fetch({
        url: '/assets/nodeInfo',
        type: "post",
        data: { key: "/asset/za-pre-product-config" },
        showRegionLoading: true,
        success: (data) => {
          this.queryNodeInfo = data ? data : [];
        },
      });

    },
  }
};
</script>
